package com.ruoyi.yl.component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.yl.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;
import com.ruoyi.common.core.utils.DateUtils;
import org.springframework.stereotype.Component;


import java.util.Date;
/**
 * @Author: linKe
 * @Date: 2022/2/18 16:50
 * @FileName: MyMetaObjectHandler
 * @version: 1.0
 * @Description: 插入更新时间的自动设置
 */

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入元对象字段填充（用于插入时对公共字段的填充）
     *
     * @param metaObject 元对象
     */

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        if(metaObject.hasSetter("createBy")){
            try {
                this.strictInsertFill(metaObject, "createBy", String.class, UserUtil.getUser());
            }catch (Exception e){
                this.strictInsertFill(metaObject, "createBy", String.class, "");
            }
        }

        if(metaObject.hasSetter("createTime")){
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now ());
        }


    }



    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        if(metaObject.hasSetter("updateBy")){
            try {
                metaObject.setValue("updateBy",null);
                this.strictUpdateFill(metaObject,"updateBy",String.class,UserUtil.getUser());
            }catch (Exception e){
                this.strictUpdateFill(metaObject,"updateBy",String.class,"");
            }
        }

        if(metaObject.hasSetter("updateTime")){
            System.out.println(DateUtils.getTime());
            metaObject.setValue("updateTime",null);
            this.strictUpdateFill(metaObject,"updateTime",LocalDateTime.class, LocalDateTime.now ());
        }

    }
}
